package com.restkeeper.store.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.restkeeper.sms.SmsObject;
import com.restkeeper.store.config.RabbitMQConfig;
import com.restkeeper.store.entity.Staff;
import com.restkeeper.store.mapper.StaffMapper;
import com.restkeeper.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 */
@Slf4j
@Service(version = "1.0.0", protocol = "dubbo")
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IStaffService {

    //秘钥
    @Value("${gateway.secret}")
    private String secret;

    @Value("${sms.operator.signName}")
    private String signName;

    @Value("${sms.operator.templateCode}")
    private String templateCode;

    @Override
    public Result login(String shopId, String loginName, String loginPass) {
        Result result = new Result();
        QueryWrapper<Staff> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(Staff::getStaffName, loginName).or().eq(Staff::getPhone, loginName).
                eq(Staff::getShopId, shopId);
        Staff staff = getBaseMapper().selectOne(queryWrapper);
       // RpcContext.getContext().setAttachment()
        //Staff staff  = this.getOne(queryWrapper);
        if (staff == null) {
            result.setStatus(ResultCode.error);
            result.setDesc("账号不存在");
            return result;
        }
        String salt = MD5CryptUtil.getSalts(staff.getPassword());
        if (!Md5Crypt.md5Crypt(loginPass.getBytes(), salt).equals(staff.getPassword())) {
            result.setStatus(ResultCode.error);
            result.setDesc("密码不正确");
            return result;
        }
        if(staff.getStatus()==SystemCode.FORBIDDEN){
            result.setStatus(ResultCode.error);
            result.setDesc("账号被禁用");
            return result;
        }
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("shopId", shopId);
        tokenMap.put("loginUserId", staff.getStaffId());
        tokenMap.put("loginUserName", loginName);
        tokenMap.put("storeId", staff.getStoreId());
        tokenMap.put("userType", SystemCode.USER_TYPE_STAFF);
        String authorization = "";
        try {
            authorization = JWTUtil.createJWTByObj(tokenMap, secret);
        } catch (Exception e) {
            log.error("加密失败{}", e.getMessage());
            result.setStatus(ResultCode.error);
            result.setDesc("加密失败");
            return result;
        }
        result.setStatus(ResultCode.success);
        result.setDesc("ok");
        result.setData(staff);
        result.setAuthorization(authorization);
        return result;
    }

    @Autowired
    private AmqpTemplate rabbitmqTemplate;

    public boolean addStaff(Staff staff) {
        //如果设置密码为空，自动生成8位密码
        String pwd = staff.getPassword();
        if (StringUtils.isEmpty(pwd)) {
            pwd = PassWordUtils.getRandom(8);
        }
        staff.setPassword(Md5Crypt.md5Crypt(pwd.getBytes()));
        boolean result = this.save(staff);
        //添加完成发送短信通知
        String shopId=RpcContext.getContext().getAttachment("shopId");
        sendMessage(staff.getPhone(),shopId,pwd);
        return  result;
    }

    @Override
    public boolean updateStaff(Staff staff) {
        Staff db =this.getById(staff.getStaffId());
        String newPwd = staff.getPassword();
        BeanUtils.copyProperties(staff,db);
        if (StringUtils.isNoneBlank(newPwd)) {
            String md5CryptPwd=Md5Crypt.md5Crypt(newPwd.getBytes());
            //修改密码短信通知
            if(!db.getPassword().equals(md5CryptPwd)){
                sendMessage(staff.getPhone(),db.getShopId(),newPwd);
            }
            db.setPassword(md5CryptPwd);
        }
        return this.updateById(db);
    }

    @Override
    public IPage<Staff> search(long page, long pageSize, String name) {
        IPage<Staff> pageResult = new Page<>(page, pageSize);
        if (Strings.isNullOrEmpty(name)) {
            return this.page(pageResult);
        }

        QueryWrapper<Staff> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .like(Staff::getStaffName, name);

        return this.page(pageResult, wrapper);
    }

    private void sendMessage(String phone, String shopId, String pwd) {
        SmsObject smsObject = new SmsObject();
        smsObject.setPhoneNumber(phone);
        smsObject.setSignName(signName);
        smsObject.setTemplateCode(templateCode);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("shopId", shopId);
        jsonObject.put("password", pwd);
        smsObject.setTemplateJsonParam(jsonObject.toJSONString());
        rabbitmqTemplate.convertAndSend(RabbitMQConfig.ACCOUNT_QUEUE, smsObject);
    }

    public static void main(String[] args) {
        System.out.println(Md5Crypt.md5Crypt("123456".getBytes()));
    }
}

 